package com.kaiyidiannao.activity.daydaycoupon;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.alipay.android.app.sdk.AliPay;
import com.com.alipay.android.msp.demo.Keys;
import com.com.alipay.android.msp.demo.Result;
import com.com.alipay.android.msp.demo.Rsa;
import com.kaiyidiannao.activity.user_detail.OrderCheck;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.common.util.AppUtils;
import com.kaiyidiannao.common.util.ArithUtils;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.data.Validate;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.ShoppingCarBean;
import com.kaiyidiannao.model.bean.UserBean;
import com.kaiyidiannao.model.req.model.PostShoppingCarOrder;
import com.kaiyidiannao.view.ActionBarView;
import com.kaiyidiannao.view.QuantitySelectorView;

import java.net.URLEncoder;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Administrator on 14-4-2.
 * 商品结算页面
 */
public class DdcPayActivity extends BaseActionBarActivity implements Observer, View.OnClickListener {
    private TextView payButton;
    private EditText mEditTel, mEditaddr;
    private TextView mTextCountMoney_sum, mTextCountMoney_transp, mTextCountMoney_product, mTextUsername;
    private Spinner mSpinerAlipyMethod;

    private String address, truename, mobile, receive, payMethod;

    private String[] paymethods;

    // 支付宝用
    public static final String TAG = "alipay-sdk";
    private static final int RQF_PAY = 1;

    private String price_transfor = 10 + ""; //运费
    private String price_product = 0 + ""; // 商品价格
    private String total_fee = 0.00 + ""; //总价格
    private String maxFare = 0 + ""; //获取单件商品的最高运费
    private String allFare = 0 + ""; //选择支付方式为"货到付款"时，运费按照单价商品累加
    private String subject = "耐克9022010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红";
    private String body = "2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红";

    // 自定义组件
    private QuantitySelectorView quantitySelectorView;
    private Map<String, String> specMap = null;
    private String[] payMethodArr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.daydaycoupon_pay_activity);
        DataCenter.getInstance().addObserver(this);

        price_product = getIntent().getStringExtra("money"); //总钱数
        ShoppingCarBean bean = (ShoppingCarBean) getIntent().getSerializableExtra("KeyNumbers");
        price_transfor = getIntent().getStringExtra("fare");//第一件商品的运费
        paymethods = getIntent().getStringExtra("paymethods").split("\\|");
        maxFare = getIntent().getStringExtra("maxFare");//运费最高的运费
        allFare = getIntent().getStringExtra("allFare");//所有商品的运费

        specMap = bean.getKeyNumbers();//规格参数
        subject = getIntent().getStringExtra("subject"); //商品标题
        body = subject;

        //处理ActionBar
        initActionBar();
        findViews();

        AppUtils.setupUI(findViewById(R.id.rootview), this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataCenter.orderid = "";
        DataCenter.getInstance().deleteObserver(this);
    }

    private void findViews() {

        mSpinerAlipyMethod = (Spinner) findViewById(R.id.daydaycoupon_alipay_method);
//        final String[] payMethodArr = getResources().getStringArray(R.array.pay_method);
       payMethodArr = paymethods;
        mSpinerAlipyMethod.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                payMethod = payMethodArr[i];
                if (payMethod.equals(getText(R.string.pay_method2)) || payMethod.equals(getText(R.string.pay_method0))) { //送货上门,支付宝支付有运费
                    mTextCountMoney_product.setText("" + price_product);
                    //支付功能要求选择支付方式为"在线支付"时，运费按单单件商品最高运费计算
                    if ( payMethod.equals(getText(R.string.pay_method0)) ) {
                        price_transfor = maxFare;
                    } else { //选择支付方式为"货到付款"时，运费按照单价商品累加
                        price_transfor = allFare;
                    }
                    total_fee = ArithUtils.add(price_product, price_transfor);

                } else { //现金自取没有运费
                    price_transfor = 0.0 + "";
                    mTextCountMoney_product.setText("" + price_product);
                    total_fee = ArithUtils.add(price_product , 0 +"");
                }
                //运费
                mTextCountMoney_transp.setText(price_transfor);
                //总价钱
                mTextCountMoney_sum.setText("" + total_fee);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        mTextUsername = (EditText) findViewById(R.id.daydaycoupon_alipay_username);
        mEditTel = (EditText) findViewById(R.id.daydaycoupon_alipay_tel);
        mEditaddr = (EditText) findViewById(R.id.daydaycoupon_alipay_address);
        mTextCountMoney_sum = (TextView) findViewById(R.id.daydaycoupon_fees_sum);//应付金额
        mTextCountMoney_product = (TextView) findViewById(R.id.daydaycoupon_fees_prodcut); //商品金额
        mTextCountMoney_transp = (TextView) findViewById(R.id.daydaycoupon_fees_transfor);

        UserBean userBean = DataCenter.userBeans.get(0);

        if (userBean != null) {
            String username = userBean.getTruename();
            if (!TextUtils.isEmpty(username)) {
                mTextUsername.setText(username);
            }
            String mobile = userBean.getMobile();
            if (!TextUtils.isEmpty(mobile)) {
                mEditTel.setText(mobile);
            }
            String address = userBean.getAddress();
            if (!TextUtils.isEmpty(address)) {
                mEditaddr.setText(address);
            }
        }

        mTextCountMoney_sum.setText(total_fee + "");//总价格
        mTextCountMoney_product.setText(price_product + ""); //产品价格
        mTextCountMoney_transp.setText(price_transfor + ""); //运费

        mSpinerAlipyMethod = (Spinner) findViewById(R.id.daydaycoupon_alipay_method);
//        public ArrayAdapter(android.content.Context context, int resource, int textViewResourceId, T[] objects)
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, android.R.id.text1,paymethods );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //就是这么简单
        mSpinerAlipyMethod.setAdapter(adapter);

        payMethod = payMethodArr[mSpinerAlipyMethod.getSelectedItemPosition()];

        receive = "快递类型";

        payButton = (TextView) findViewById(R.id.daydaycoupon_confirm);
        payButton.setOnClickListener(DdcPayActivity.this);
    }

    private boolean cheakUpdate() {

        boolean flag = true;

        // 收件人
        truename = mTextUsername.getText().toString().trim();
        if (isEmpty(truename)) {
            showToast("收件人不能为空");
            return false;
        }

        // 手机号码
        mobile = mEditTel.getText().toString().trim();
        if (isEmpty(mobile)) {
            showToast("手机号码不能为空");
            return false;
        }
        if (!mobile.matches(Validate.phoneValidate)) {
            showToast("手机号码不正确");
            return false;
        }

        // 收件地址
        address = mEditaddr.getText().toString().trim();
        if (isEmpty(address)) {
            showToast("收货地址不能为空");
            return false;
        }
        if (address.length() <= 6 || address.length()>=30) {
            showToast("收货地址为6-30位，不能输入空格");
            return false;
        }


        return flag;
    }

    private boolean isEmpty(String character) {
        return TextUtils.isEmpty(character.trim().toString());
    }

    //-------------------------------------------支付宝start----------------------------------------------------------

    /**
     * 支付宝支付方式
     */
    private void initAlipayMethod() {
        try {
            String info = getNewOrderInfo(0);
            String sign = Rsa.sign(info, Keys.PRIVATE);
            sign = URLEncoder.encode(sign);
            info += "&sign=\"" + sign + "\"&" + getSignType();
            // start the pay.
            Log.i(TAG, "info = " + info);

            final String orderInfo = info;
            new Thread() {
                public void run() {
                    AliPay alipay = new AliPay(DdcPayActivity.this, mHandler);

                    //设置为沙箱模式，不设置默认为线上环境
                    //alipay.setSandBox(true);

                    String result = alipay.pay(orderInfo);

                    Log.i(TAG, "Result---------------:" + result + "!");
                    Result rs = new Result(result);

                    Message msg = new Message();
                    msg.what = RQF_PAY;
                    msg.obj = rs.getResult();
                    msg.arg1 = rs.getResultCode();
                    Log.i(TAG, "result = " + msg.obj);
                    mHandler.sendMessage(msg);
                }
            }.start();

        } catch (Exception ex) {
            ex.printStackTrace();
            //showToast(R.string.remote_call_failed);
            showToast("Failure calling remote service");
        }
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            String resultMSG = msg.obj.toString();//提示信息
            int code = msg.arg1; //状态码制


            Log.i(TAG, "mHandler = !" + resultMSG + "!");

            // 在这里进行回调处理
            switch (msg.what) {
                case RQF_PAY:
                    if (code == 9000) { //支付成功
                        paySucess();
                        showToast(resultMSG);
                    } else {
                        payFaild();
                        showToast(resultMSG, "支付失败");
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    private void payFaild() {
        // 1：关闭当前页面
        finish();
        // 2:t跳转到订单页面
        Intent intent = new Intent(DdcPayActivity.this, OrderCheck.class);
        intent.putExtra("orderCheck", "orderCheck");
        startActivity(intent);
    }

    private void paySucess() {
        // 1：关闭当前页面
        finish();
        // 2：跳转到支付成功页面
        Intent intent = new Intent(DdcPayActivity.this, DdcShoppingSucessActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);

        bundle.putString("product_id", getOutTradeNo()); //订单号
        bundle.putString("alipay_method", payMethod + ""); //
        bundle.putString("price_count", total_fee + "");
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private String getNewOrderInfo(int position) {
        StringBuilder sb = new StringBuilder();
        sb.append("partner=\"");
        sb.append(Keys.DEFAULT_PARTNER);
        sb.append("\"&out_trade_no=\"");
        sb.append(getOutTradeNo());
        sb.append("\"&subject=\"");
        sb.append(subject);
        sb.append("\"&body=\"");
        sb.append(body);
        sb.append("\"&total_fee=\"");
        sb.append(total_fee + "");
        sb.append("\"&notify_url=\"");

        // 网址需要做URL编码
        sb.append(URLEncoder.encode("http://www.3tixa.com:8086/kaiyi/api/pay/alipay/notify.php"));
        sb.append("\"&service=\"mobile.securitypay.pay");
        sb.append("\"&_input_charset=\"UTF-8");
        sb.append("\"&return_url=\"");
        sb.append(URLEncoder.encode("http://m.alipay.com"));
        sb.append("\"&payment_type=\"1");
        sb.append("\"&seller_id=\"");
        sb.append(Keys.DEFAULT_SELLER);

        // 如果show_url值为空，可不传
        // sb.append("\"&show_url=\"");
        sb.append("\"&it_b_pay=\"1m");
        sb.append("\"");

        return new String(sb);
    }

    // 获取订单号码
    private String getOutTradeNo() {
//        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
//        Date date = new Date();
//        String key = format.format(date);
//
//        java.util.Random r = new java.util.Random();
//        key += r.nextInt();
//        key = key.substring(0, 15);
//        Log.d(TAG, "outTradeNo: " + key);

        String key = DataCenter.orderid;
        return key;
    }

    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    //-------------------------------------------支付宝end----------------------------------------------------------
    private void initActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.setTitle("支付");
    }


    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;
        closeProgressDialog();

        if (flag == DataCenter.flag.SHOPPING_CAR_RESULT_DATA_ORDER_SUCCESS) { //获取订单成功
            // 具体的支付操作
            if (payMethod.equals(getResources().getStringArray(R.array.pay_method)[0])) { //支付宝
                initAlipayMethod();
            } else if (payMethod.equals(getResources().getStringArray(R.array.pay_method)[1])) { //现金自取
                paySucess();
            } else {//送货上门
                paySucess();
            }
        } else if (flag == DataCenter.flag.SHOPPING_CAR_RESULT_DATA_ORDER_FAILED) {//获取订单失败
            showToast(DataCenter.msg, "获取订单失败");
        } else if (flag == DataCenter.flag.REQUEST_COMMON_FAILDED) {
            closeProgressDialog();
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.daydaycoupon_confirm: //点击支付按钮
                // 获取订单
                if (cheakUpdate() && isLogin()) {
                    String userid = DataCenter.userLogin.get(0).getUserid();
                    showProgressDialog();
                    new PostShoppingCarOrder(userid, specMap, address, truename, mobile, receive, total_fee + "", payMethod,price_transfor).execute();
                }
                break;
            default:
        }
    }
}
